package cn.yujiago.shiro.realm;

import cn.yujiago.shiro.domain.RoleDO;
import cn.yujiago.shiro.domain.UserDO;
import cn.yujiago.shiro.service.MenuService;
import cn.yujiago.shiro.service.RoleService;
import cn.yujiago.shiro.service.UserService;
import cn.yujiago.shiro.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("--------开始授权--------");

        //获取用户
        UserDO user = (UserDO) SecurityUtils.getSubject().getPrincipal();

        // 角色
        List<RoleDO> roles = roleService.getRoles(user.getId());
        Set<String> roleSet = new HashSet<>();
        for(RoleDO role : roles){
            roleSet.add(role.getRoleSign());
        }
        // 权限
        Set<String> permsSet = menuService.getPermsByUserId(user.getId());

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 注意权限Set中不能含有null，要么在set中处理，要么在sql中处理
        roleSet.remove(null);
        permsSet.remove(null);
        info.addRoles(roleSet);
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("--------开始认证--------");

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        UserDO user = userService.getUser(token.getUsername());

        // 账号不存在
        if (user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }

        // 密码错误
//        if (!password.equals(user.getPassword())) {
//            throw new IncorrectCredentialsException("账号或密码不正确");
//        }

        // 账号锁定
        if (user.getStatus() == 1) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }

        SimpleAuthenticationInfo info = ShiroUtils.getSimpleAuthenticationInfo(user, user.getPassword(), token.getUsername(), this.getName());

        return info;
    }
}
